package com.zmn.brs.admin.controller.rule.order;

import com.alibaba.fastjson.JSONObject;
import com.zmn.brs.admin.controller.rule.base.AlarmRuleBaseController;
import com.zmn.brs.business.interfaces.rule.AlarmRuleBService;
import com.zmn.brs.common.constant.RedisKeyConst;
import com.zmn.brs.common.enums.EventTypeEnum;
import com.zmn.brs.common.enums.ThresholdExpressionEnum;
import com.zmn.brs.model.entity.event.Event;
import com.zmn.brs.model.entity.threshold.Threshold;
import com.zmn.brs.model.query.rule.OrderRuleCustomQuery;
import com.zmn.brs.model.vo.rule.ComparisonRuleVO;
import com.zmn.brs.model.vo.rule.QuantityRuleVO;
import com.zmn.brs.model.vo.rule.common.OrderRuleVO;
import com.zmn.brs.services.interfaces.event.EventService;
import com.zmn.brs.services.interfaces.threshold.ThresholdService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 描述： 规则
 * @author chongw
 * @since 2021-05-28 17:05:29
 */
@RestController
@RequestMapping("/brs/oreder/rule/")
public class OrderRuleModifyController extends AlarmRuleBaseController {

    @Resource
    private AlarmRuleBService alarmRuleBService;

    @Resource
    private ThresholdService thresholdService;

    @Resource
    private EventService eventService;

    /**
     * 保存人单比规则配置
     * @param comparisonRuleVO
     * @return
     */
    @ResponseBody
    @RequestMapping("comparison/addEdit")
    public ResponseDTO addEditComparison(@RequestBody ComparisonRuleVO comparisonRuleVO){
        try {
            Date now = DateUtil.getNow();
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getEventId())) {
                return ResponseDTO.fail("参数不能为空");
            }
            if (comparisonRuleVO.getValue() == null){
                return ResponseDTO.fail("人单比阈值不能为空");
            }
            if(comparisonRuleVO.getValue() < 0) {
                return ResponseDTO.fail("人单比阈值必须大于等于0");
            }
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getProvinceId())) {
                return ResponseDTO.fail("省份不能为空");
            }
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getCityId())) {
                return ResponseDTO.fail("城市不能为空");
            }
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getServClusterType())) {
                return ResponseDTO.fail("业务类型不能为空");
            }
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getServClusterId())) {
                return ResponseDTO.fail("业务线不能为空");
            }
            if (NumberUtil.isNullOrZero(comparisonRuleVO.getServGroupId())) {
                return ResponseDTO.fail("产品组不能为空");
            }
            //查询规则ID
            Integer ruleId = alarmRuleBService.findRuleIdByEventId(comparisonRuleVO.getEventId());

            //获取唯一key
            String uniqueNo = RedisKeyConst.getCacheRuleConfigRedisKey(EventTypeEnum.COMPARISON.getTypeId(),comparisonRuleVO.getCityId()
                    , comparisonRuleVO.getServGroupId()
            );
            comparisonRuleVO.setUniqueNo(uniqueNo);

            //判断是否存在
            Integer count = alarmRuleBService.countOrderRuleExistByQuery(OrderRuleCustomQuery.builder()
                    .thresholdId(comparisonRuleVO.getThresholdId())
                    .uniqueNo(uniqueNo)
                    .build());
            if(count > 0){
                return ResponseDTO.fail(String.format("已存在【%s.%s】人单比配置！！", comparisonRuleVO.getCityName() ,
                        comparisonRuleVO.getServGroupName()));
            }
            AtomicReference<Integer> flag = new AtomicReference<>(0);

            //新增
            if(NumberUtil.isNullOrZero(comparisonRuleVO.getThresholdId())){

                //阈值
                Threshold threshold = Threshold.builder()
                        .ruleId(ruleId)
                        .thresholdName(String.format("%s.%s-人单比阈值", comparisonRuleVO.getCityName()
                                ,comparisonRuleVO.getServGroupName()))
                        .type(0)
                        .thresholdParam(String.valueOf(comparisonRuleVO.getEventId()))
                        .expression(ThresholdExpressionEnum.ALL.getExpression())
                        .thresholdValue(JSONObject.toJSONString(comparisonRuleVO))
                        .creater(super.getMcStaffRealName())
                        .updater(super.getMcStaffRealName())
                        .createTime(now)
                        .updateTime(now)
                        .build();

                flag.updateAndGet(v -> v + thresholdService.insert(threshold));

                if(flag.get() > 0) {
                    //写入缓存
                    alarmRuleBService.cacheRule(uniqueNo, comparisonRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            //修改
            else{

                Threshold threshold = thresholdService.findById(comparisonRuleVO.getThresholdId());
                ComparisonRuleVO vo = JSONObject.parseObject(threshold.getThresholdValue() , ComparisonRuleVO.class);
                //获取上次rediskey
                String oldRedisKey = vo.getUniqueNo();

                vo.setPlat(comparisonRuleVO.getPlat());
                vo.setPlatName(comparisonRuleVO.getPlatName());
                vo.setProvinceId(comparisonRuleVO.getProvinceId());
                vo.setProvinceName(comparisonRuleVO.getProvinceName());
                vo.setCityId(comparisonRuleVO.getCityId());
                vo.setCityName(comparisonRuleVO.getCityName());
                vo.setServClusterId(comparisonRuleVO.getServClusterId());
                vo.setServClusterName(comparisonRuleVO.getServClusterName());
                vo.setServClusterType(comparisonRuleVO.getServClusterType());
                vo.setServClusterTypeName(comparisonRuleVO.getServClusterTypeName());
                vo.setServGroupId(comparisonRuleVO.getServGroupId());
                vo.setServGroupName(comparisonRuleVO.getServGroupName());
                vo.setValue(comparisonRuleVO.getValue());
                vo.setUniqueNo(uniqueNo);

                threshold.setThresholdName(String.format("%s.%s-人单比阈值", comparisonRuleVO.getCityName()
                        ,comparisonRuleVO.getServGroupName()));
                threshold.setThresholdValue(JSONObject.toJSONString(vo));
                threshold.setUpdateTime(now);
                threshold.setUpdater(super.getMcStaffRealName());

                flag.updateAndGet(v -> v + thresholdService.updateByKey(threshold));
                if(flag.get() > 0) {
                    //写入缓存
                    alarmRuleBService.cacheRule(uniqueNo, oldRedisKey, comparisonRuleVO.getEventId(), threshold.getThresholdId());
                }
            }
            if(flag.get() > 0){
                return ResponseDTO.success();
            }
        }catch (Exception e){
            logger.error("保存人单比规则配置异常，异常信息：" + e);
            e.printStackTrace();
        }
        return ResponseDTO.fail("保存人单比规则配置失败");
    }

    /**
     * 保存整体单量规则配置
     * @param quantityRuleVO
     * @return
     */
    @ResponseBody
    @RequestMapping("quantity/addEdit")
    public ResponseDTO addEditQuantity(@RequestBody QuantityRuleVO quantityRuleVO){
        try {
            Date now = DateUtil.getNow();
            if (NumberUtil.isNullOrZero(quantityRuleVO.getEventId())) {
                return ResponseDTO.fail("参数不能为空");
            }
            if (!NumberUtil.isPositiveInteger(quantityRuleVO.getValue())) {
                return ResponseDTO.fail("整体单量阈值必须大于0");
            }
            if (NumberUtil.isNullOrZero(quantityRuleVO.getProvinceId())) {
                return ResponseDTO.fail("省份不能为空");
            }
            if (NumberUtil.isNullOrZero(quantityRuleVO.getCityId())) {
                return ResponseDTO.fail("城市不能为空");
            }
            //查询规则ID
            Integer ruleId = alarmRuleBService.findRuleIdByEventId(quantityRuleVO.getEventId());

            //获取唯一key
            String uniqueNo = RedisKeyConst.getCacheRuleConfigRedisKey(EventTypeEnum.QUANTITY.getTypeId(), quantityRuleVO.getCityId());
            quantityRuleVO.setUniqueNo(uniqueNo);

            //判断是否存在
            Integer count = alarmRuleBService.countOrderRuleExistByQuery(OrderRuleCustomQuery.builder()
                    .thresholdId(quantityRuleVO.getThresholdId())
                    .uniqueNo(uniqueNo)
                    .build());
            if(count > 0){
                return ResponseDTO.fail(String.format("已存在【%s】整单量配置！！", quantityRuleVO.getCityName()));
            }

            quantityRuleVO.setMcStaffName(super.getMcStaffRealName());

            AtomicReference<Integer> flag = new AtomicReference<>(0);

            //新增
            if(NumberUtil.isNullOrZero(quantityRuleVO.getThresholdId())){

                //阈值
                Threshold threshold = Threshold.builder()
                        .ruleId(ruleId)
                        .thresholdName(String.format("[%s]-整体单量阈值", quantityRuleVO.getCityName()))
                        .type(0)
                        .thresholdParam(String.valueOf(quantityRuleVO.getEventId()))
                        .expression(ThresholdExpressionEnum.ALL.getExpression())
                        .thresholdValue(JSONObject.toJSONString(quantityRuleVO))
                        .creater(quantityRuleVO.getMcStaffName())
                        .updater(quantityRuleVO.getMcStaffName())
                        .createTime(now)
                        .updateTime(now)
                        .build();

                flag.updateAndGet(v -> v + thresholdService.insert(threshold));
                if(flag.get() > 0) {
                    //写入缓存
                    alarmRuleBService.cacheRule(uniqueNo, quantityRuleVO.getEventId(), threshold.getThresholdId());
                }

            }
            //修改
            else{

                Threshold threshold = thresholdService.findById(quantityRuleVO.getThresholdId());
                QuantityRuleVO vo = JSONObject.parseObject(threshold.getThresholdValue() , QuantityRuleVO.class);
                //获取上次rediskey
                String oldRedisKey = vo.getUniqueNo();

                vo.setPlat(quantityRuleVO.getPlat());
                vo.setPlatName(quantityRuleVO.getPlatName());
                vo.setProvinceId(quantityRuleVO.getProvinceId());
                vo.setProvinceName(quantityRuleVO.getProvinceName());
                vo.setCityId(quantityRuleVO.getCityId());
                vo.setCityName(quantityRuleVO.getCityName());
                vo.setUniqueNo(uniqueNo);
                vo.setValue(quantityRuleVO.getValue());
                vo.setMcStaffName(super.getMcStaffRealName());

                threshold.setThresholdName(String.format("[%s]-整体单量阈值", quantityRuleVO.getCityName()));
                threshold.setThresholdValue(JSONObject.toJSONString(vo));
                threshold.setUpdateTime(now);
                threshold.setUpdater(super.getMcStaffRealName());

                flag.updateAndGet(v -> v + thresholdService.updateByKey(threshold));
                if(flag.get() > 0) {
                    //写入缓存
                    alarmRuleBService.cacheRule(uniqueNo, oldRedisKey, quantityRuleVO.getEventId(), threshold.getThresholdId());
                }
            }

            if(flag.get() > 0){
                return ResponseDTO.success();
            }
        }catch (Exception e){
            logger.error("保存整体单量规则配置异常，异常信息：" + e);
            e.printStackTrace();
        }
        return ResponseDTO.fail("保存整体单量规则配置失败");
    }


    /**
     * 保存公共阈值规则配置
     * @param vo
     * @return
     */
    @ResponseBody
    @RequestMapping("common/addEdit")
    public ResponseDTO addEditCommon(@RequestBody OrderRuleVO vo){
        try {
            if (NumberUtil.isNullOrZero(vo.getEventId())) {
                return ResponseDTO.fail("事件ID参数不能为空");
            }
            if (NumberUtil.isNullOrZero(vo.getRuleId())) {
                return ResponseDTO.fail("规则ID参数不能为空");
            }
            if (!NumberUtil.isPositiveDouble(vo.getValue())) {
                return ResponseDTO.fail("预警百分比阈值必须大于0");
            }
            //获取事件信息
            Event event = eventService.findById(vo.getEventId());
            event.setUpdater(super.getMcStaffRealName());
            //设置JSON对象
            JSONObject data = (JSONObject)JSONObject.toJSON(vo);
            event.setCommon(data);
            //修改公共阈值
            Integer flag = alarmRuleBService.upsertEventCommonRule(event);
            if(flag > 0){
                return ResponseDTO.success();
            }
        }catch (Exception e){
            logger.error("保存预警百分比规则配置异常，异常信息：" + e);
            e.printStackTrace();
        }
        return ResponseDTO.fail("保存预警百分比规则配置失败");
    }

}
